import axios from 'axios'
import router from "./router/index"
import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);
let toast = null;

axios.defaults.baseURL = 'https://www.risesin.com/api'  // 生产
// axios.defaults.baseURL = '/api'  // 开发

// 请求拦截器
axios.interceptors.request.use(config => {
  toast = Toast.loading({
    message: '加载中...',
    duration: 9999999,
    forbidClick: true,
  });

  // 下载文件加个请求头
  if(config.data.fileName) {
    config.responseType = 'blob'
  }

  if (localStorage.token) {
    config.headers['r-token'] = localStorage.token
  }
  return config;
}, error => Promise.reject(error));

// 响应拦截器

axios.interceptors.response.use(
  response => {
    switch(response.data.code) {
      // 成功
      case 0:
        toast.clear();
        return response.data;
      // token失效
      case 100:
        alert(response.data.message);
        localStorage.removeItem("token");
        localStorage.removeItem("isLogin");
        localStorage.removeItem("userInfo");
        localStorage.removeItem("openId");
        window.location.href = 'https://www.risesin.com/h5'
        toast.clear();
        return false;
      case 101:
        alert(response.data.message);
        localStorage.removeItem("token");
        localStorage.removeItem("isLogin");
        localStorage.removeItem("userInfo");
        localStorage.removeItem("openId");
        window.location.href = 'https://www.risesin.com/h5'
        toast.clear();
        return false;
      default:
        toast.clear();
        Toast(response.data.message)
        return response.data;
    }
  },
  error => Promise.reject(error)
)

// axios.post 请求

/* eslint-disable */
export const $post = async (path, data = {}) => await axios.post(path, data);

// axios.get 请求

/* eslint-disable */
export const $get = async (path, params = {}) => await axios.get(path, params);


/**
 * 
 *  当然你也可以用 Promise 
 *  export const $get = (path, params = {}) => {
 *      new Promise((resolve, reject) => {
 *          axios.get(path, params)
 *            .then(res => resolve(res))
 *            .catch(err => reject(err))
 *      })
 *  }
 * 
 */ 